package ca.uwindsor;

import java.util.Date;

import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;

public class NotificationService extends IntentService {

    public NotificationService() 
    { 
        super("myintentservice"); 
    } 
    
	private static int TEST_ID = 1;
    
    @Override 
    protected void onHandleIntent(Intent intent) { 
    	
    	while(true){
    	final MyDBAdapter db = new MyDBAdapter(getApplicationContext());
    	db.open();
    	db.setDATABASE_TABLE("event_schedule");
    	Common c = new Common();
    	Date date = new Date();
    	
    	Cursor ret = db.getEntry("Date",c.DateToString(date, "yyyy-MM-dd")) ;
    	
    	while(ret.moveToNext()){
    		
    		String ns = Context.NOTIFICATION_SERVICE;
    		NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
    		
    		int icon = R.drawable.icon;
    		CharSequence tickerText = ret.getString(2)+" "+ret.getString(5);
    		
    		long when = System.currentTimeMillis();

    		Notification notification = new Notification(icon, tickerText, when);
    		
    		Context context = getApplicationContext();
    		CharSequence contentTitle = "Assigment/Exam Alert";
    		CharSequence contentText = ret.getString(2)+" "+ret.getString(5)+" from "+ ret.getString(3)+" to "+ret.getString(4);
    		Intent notificationIntent = new Intent(this, NotificationService.class);
    		PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

    		notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
    		
    		mNotificationManager.notify(TEST_ID,notification);
    		TEST_ID += 1;
    	}
    	
    	
    	db.close();
    	
    	//wait for some time and check again.
    	 long endTime = System.currentTimeMillis() + 12*60*60*1000;
         while (System.currentTimeMillis() < endTime) {
             synchronized (this) {
                 try {
                     wait(endTime - System.currentTimeMillis());
                 } catch (Exception e) {
                 }
             }
         }
		
    	}
    	
        
    }

}
